package com.rds.mongodb.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.rds.mongodb.entity.FileDocument;
import com.rds.mongodb.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 文件上传下载控制层
 *
 * @author Lin Zemin
 * @date 2020-10-28
 */
@Controller
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 进入首页
     * @param model model类
     * @return String
     */
    @RequestMapping(value = "/")
    public String index(Model model) {
        // 展示最新二十条数据
        model.addAttribute("files", fileService.listFilesByPage(0, 20));
        return "index";
    }


    /**
     * 分页查询文件
     * @param pageIndex 第几页
     * @param pageSize 每页条数
     * @return List<FileDocument>
     */
    @GetMapping("files/{pageIndex}/{pageSize}")
    @ResponseBody
    public List<FileDocument> listFilesByPage(@PathVariable int pageIndex, @PathVariable int pageSize) {
        return fileService.listFilesByPage(pageIndex, pageSize);
    }

    /**
     * 通过文件id获取文件
     * @param id 文件id
     * @return ResponseEntity<Object>
     * @throws UnsupportedEncodingException 编码异常
     */
    @GetMapping("files/{id}")
    @ResponseBody
    public ResponseEntity<Object> serveFile(@PathVariable String id) throws UnsupportedEncodingException {

        Optional<FileDocument> file = fileService.getFileById(id);

        if (file.isPresent()) {
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; fileName=" + URLEncoder.encode(file.get().getName(), "UTF-8"))
                    .header(HttpHeaders.CONTENT_TYPE, "application/octet-stream")
                    .header(HttpHeaders.CONTENT_LENGTH, file.get().getSize() + "").header("Connection", "close")
                    .body(file.get().getContent());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File was not fount");
        }

    }

    /**
     * 在线显示文件
     */
    @GetMapping("/view")
    @ResponseBody
    public ResponseEntity<Object> serveFileOnline(@RequestParam("id") String id) {
        Optional<FileDocument> file = fileService.getFileById(id);
        return file.<ResponseEntity<Object>>map(fileDocument -> ResponseEntity.ok()
                                                .header(HttpHeaders.CONTENT_DISPOSITION, "fileName=" + fileDocument.getName())
                                                .header(HttpHeaders.CONTENT_TYPE, fileDocument.getContentType())
                                                .header(HttpHeaders.CONTENT_LENGTH, fileDocument.getSize() + "")
                                                .header("Connection", "close")
                                                .header(HttpHeaders.CONTENT_LENGTH, fileDocument.getSize() + "")
                                                .body(fileDocument.getContent()))
                                           .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body("File was not found"));


    }

    /**
     * 上传文件
     * @param file 文件
     * @return String
     */
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {

        try {
            if(file != null && file.getOriginalFilename() != null) {
                FileDocument fileDocument = new FileDocument();
                fileDocument.setName(file.getOriginalFilename());
                fileDocument.setSize(file.getSize());
                fileDocument.setContentType(file.getContentType());
                fileDocument.setUploadDate(new Date());
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                fileDocument.setSuffix(suffix);
                fileDocument.setMd5(DigestUtil.md5Hex(file.getInputStream()));
                //将文件存入gridFs
                String gridfsId = fileService.uploadFileToGridFs(file.getInputStream() , file.getContentType());
                fileDocument.setGridfsId(gridfsId);
                fileDocument = fileService.saveFile(fileDocument);
                System.out.println(fileDocument);
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return "redirect:/";
    }


    /**
     * 删除文件
     * @param id 文件id
     * @return String
     */
    @GetMapping("/delete")
    public String deleteFile(@RequestParam("id") String id) {
            fileService.removeFile(id);
        return "redirect:/";
    }

    /**
     * 下载文件
     * @param id 文件id
     * @param response 响应类
     */
    @GetMapping("/downLoadFile")
    public void downLoadFile(HttpServletResponse response, @RequestParam("id") String id) {
        fileService.downLoadFile(response, id);

    }
}
